package de.tum.in.elitese.wahlsys.controller;

import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;

import de.tum.in.elitese.wahlsys.common.DbService;
import de.tum.in.elitese.wahlsys.common.DbServiceFactrory;
import de.tum.in.elitese.wahlsys.common.KnownExecption;
import de.tum.in.elitese.wahlsys.common.data.UserCredentials;
import de.tum.in.elitese.wahlsys.common.data.UserType;
import de.tum.in.elitese.wahlsys.controller.beans.VotingBoothsBean;

/**
 * ControllerBean for the login.jsp<br /> It checks and saves the user
 * credentials and redirects to the next page according to the user type
 * 
 * @author christoph
 */
public class LoginController {

	private UserCredentials fCredentials;
	private String fName;
	private String fPassword;
	private VotingBoothsBean fVotingBoothsBean;

	public UserCredentials getCredentials() {
		return fCredentials;
	}

	public String getName() {
		return fName;
	}

	public String getPassword() {
		// should never be returned
		return null;
	}

	/**
	 * Action Handler Method for the login attempt
	 * 
	 * @return the navigation outcome
	 */
	public String login() {

		// check db for credentials
		DbService db = DbServiceFactrory.getInstance().createDbService();
		try {
			fCredentials = db.getUserCredentials(fName, fPassword);
		} catch (KnownExecption e) {
			FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(e.getMessage()));
			e.printStackTrace();
			return null;
		}

		// error
		if (fCredentials == null) {
			FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Benutzername oder Password falsch!"));
			return null;
		}

		// if user is a voting booth then add it to the list of voting booths so
		// that voters can be assigned to it
		if (fCredentials.getUserType() == UserType.VOTING_BOOTH) {
			fVotingBoothsBean.addVotingBooth(fCredentials);
		}

		return fCredentials.getUserType().name();
	}

	public void setCredentials(UserCredentials credentials) {
		fCredentials = credentials;
	}

	public void setName(String name) {
		fName = name;
	}

	public void setPassword(String password) {
		fPassword = password;
	}

	public void setVotingBoothsBean(VotingBoothsBean votingBoothsBean) {
		fVotingBoothsBean = votingBoothsBean;
	}
}
